/*
 * @Author: Wangtao
 * @Date: 2020-11-11 21:21:21
 * @LastEditors: zhanwang
 * @LastEditTime: 2021-12-29 15:13:50
 */
import { VuexModule, Module, Mutation, getModule, Action } from 'vuex-module-decorators'
import store from '@/store'
import Vue from 'vue'
import router from '@/router/handleRoute'
import { commonAction, checkHideTel } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'

export interface ICardState {
  callInList: object[],
  outboundList: object[],
  isInit: any,
  currentOutboundObj: any
}

@Module({ dynamic: true, store, name: 'CallCardModel', namespaced: false })

class CallCardModel extends VuexModule implements ICardState {
  public callInList = []
  public outboundList = []
  public maxListNumber = 20

  public currentOutboundObj = {}

  public isInit = false

  @Mutation
  private ADD_CALL_CARD ({ type, cardObj }) {
    let currentListName: any
    if (type === 'cdr_call') {
      currentListName = 'callInList'
    }
    if (type === 'cdr_outbound') {
      currentListName = 'outboundList'
    }

    const currentList = this[currentListName] || []
    if (currentList && currentList.length >= 20) {
      currentList.pop()
    }
    currentList.unshift(cardObj)
    const key = store.state.common.session.user._id
    Vue.set(this, currentListName, currentList)
    // if (type === 'cdr_outbound') {
    //   Vue.set(this, 'currentOutboundObj', currentList[0])
    // }
    window.sessionStorage.setItem(type, JSON.stringify(currentList))
  }

  @Mutation
  private UPDATE_CALL_CARD ({ type, id, event, eventTime, body }) {
    let currentListName: any
    if (type === 'cdr_call') {
      currentListName = 'callInList'
    }
    if (type === 'cdr_outbound') {
      currentListName = 'outboundList'
    }
    const linkStatus = ['4', '6', '7', '10', '11', '12'] // 通话中, 保持，静音,咨询方，三方，被咨询方
    const currentList = this[currentListName]
    currentList.some((item, index) => {
      if (item.id === id) {
        item.eventTime = eventTime
        if (event === 'hangup') {
          item.event === 'link' ? item.event = 'Answered' : item.event = 'noAnswered'
        } else if (linkStatus.indexOf(body && body.statusNumber) > -1) {
          item.event = 'link'
        } else {
          item.event = event
        }
        return true
      }
    })
    Vue.set(this, currentListName, currentList)
    window.sessionStorage.setItem(type, JSON.stringify(currentList))
  }

  @Mutation
  public RMOVE_CALL_CARD ({ type, id }) {
    let currentListName: any
    let deleteIndex: any
    if (type === 'cdr_call') {
      currentListName = 'callInList'
    }
    if (type === 'cdr_outbound') {
      currentListName = 'outboundList'
    }
    const currentList = this[currentListName]
    if (currentList && currentList.length > 0) {
      currentList.some((item, index) => {
        if (item.id === id) {
          deleteIndex = index
          return true
        }
      })
      currentList.splice(deleteIndex, 1)
    }
    Vue.set(this, currentListName, currentList)
    window.sessionStorage.setItem(type, JSON.stringify(currentList))
    if (router.currentRoute.params.id === id) {
      router.push({ path: '/call_workBench/index/' + type + '/empty' })
    }
  }

  @Action({ rawError: true })
  public async proxyCard (data: any) {
    this.INIT_CARD()
    if (data && data.body) {
      let setType
      const callData = data.body
      if (data.body.callType && ['incoming', 'transfer', 'consultTransfer', 'webcall'].indexOf(data.body.callType) > -1) {
        setType = 'cdr_call'
      } else if (data.body.callType === 'dialout' || data.body.callType === 'previewDialout') {
        setType = 'cdr_outbound'
      } else {
        return false
      }
      let currentListName: any
      let exist: boolean = false
      if (setType === 'cdr_call') {
        currentListName = 'callInList'
      }
      if (setType === 'cdr_outbound') {
        currentListName = 'outboundList'
      }
      const currentList = this[currentListName]
      if (currentList && currentList.length > 0) {
        currentList.some((item) => {
          if (item.id === callData.superUniqueId) {
            exist = true
            return true
          }
        })
      }
      if (!exist) {
        if (callData.callType === 'dialout' && callData.callEvent !== 'calling') {
          return
        }
        if (callData.callType === 'incoming' && callData.callEvent !== 'ring') {
          return
        }
        this.ADD_CALL_CARD({ type: setType, cardObj: { id: callData.superUniqueId, event: callData.callEvent, custName: '未知客户', phoneNum: callData.number, eventTime: data.timestamp, body: callData } })
        this.SET_CUSTOMER_NAME({ setType, phone: callData.number, id: callData.superUniqueId, custObj: {} })
        const options = {
          dir: 'auto',
          icon: 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=405069346,3880007726&fm=11&gp=0.jpg',
          body: ''
        }
        const routePath = `/call_workBench/index/${setType}/${callData.superUniqueId}?phone=${callData.number}`
        const message = '您有新电话卡片'
        const notifyTitle = '通知'
        options.body = message
        CommonModule.NOTIFY({
          title: notifyTitle,
          message,
          options,
          routePath,
          notifyData: {}
        })
        if (callData.callType === 'dialout' && !callData.taskId && store.state.common.session.user?.autoOutCall) { // 判断是不是外呼任务和有没有在设置中选择
          setTimeout(() => {
            router.push({ path: routePath })
          }, 1000);
        }
      } else {
        this.UPDATE_CALL_CARD({ type: setType, id: callData.superUniqueId, event: callData.callEvent, eventTime: data.timestamp, body: callData })
      }
    }
  }
  /**
   * setType 呼叫类型 required
   * phone 号码 required
   * id 通话id  required
   * custObj { name 更新客户名称， id 通话id}
   */

  @Action({ rawError: true })
  public async SET_CUSTOMER_NAME ({ setType, phone, id, custObj }) {
    this.INIT_CARD()
    let currentListName: any
    if (setType === 'cdr_call') {
      currentListName = 'callInList'
    }
    if (setType === 'cdr_outbound') {
      currentListName = 'outboundList'
    }
    const currentList = this[currentListName]
    if (custObj && Object.keys(custObj).length > 0) {
      if (currentList && currentList.length > 0) {
        currentList.some((item, index) => {
          if (item.id === id) {
            currentList[index].custName = custObj.name
            currentList[index].custId = custObj.id
          }
          if (item.custId === custObj.id) {
            currentList[index].custName = custObj.name
          }
          if (item.phoneNum === phone) {
            currentList[index].locateCust = custObj.customerList
          }
        })
        this.SET_CALL_CARD({ setName: currentListName, setType, list: currentList })
        this.SET_CURRENT_OUTBOUND_OBJ({ setType, list: currentList })
      }
    } else {
      this.CdrLocateCust({ type: 1, phone }).then((res) => {
        if (res.success && res.data && res.data.length > 0) {
          const customList = res.data
          currentList.some((item, index) => {
            if (item.id === id) {
              if (customList.length === 1) {
                currentList[index].custName = customList[0].name
                currentList[index].custId = customList[0].id
              } else if (customList.length > 1) {
                currentList[index].custName = '多个客户'
              } else {
                currentList[index].custName = '未知客户'
              }
              currentList[index].locateCust = customList
              return true
            }
          })
          this.SET_CALL_CARD({ setName: currentListName, setType, list: currentList })
        }
        this.SET_CURRENT_OUTBOUND_OBJ({ setType, list: currentList })
      })
    }
  }

  @Mutation
  private SET_CALL_CARD ({ setName, setType, list }) {
    Vue.set(this, setName, list)
    window.sessionStorage.setItem(setType, JSON.stringify(list))
  }

  @Mutation
  private SET_CURRENT_OUTBOUND_OBJ ({ setType, list }) { // 用于外呼弹屏的触发
    if (setType === 'cdr_outbound') {
      Vue.set(this, 'currentOutboundObj', list[0] || {})
    }
  }

  @Mutation
  public async GET_CURRENT_LIST (type) {
    let currentListName: any
    if (type === 'cdr_call') {
      currentListName = 'callInList'
    }
    if (type === 'cdr_outbound') {
      currentListName = 'outboundList'
    }
    return this[currentListName]
  }

  @Mutation
  public async INIT_CARD () {
    if (!this.isInit) {
      this.isInit = true
      const callInList = JSON.parse((window as any).sessionStorage.getItem('cdr_call'))
      if (callInList && callInList.length > 0) {
        callInList.forEach(item => {
          if (item.body && item.body.number) {
            item.body.hideTel = checkHideTel(item.body.number) // 缓存里面的要重新走一遍权限
          }
        })
        Vue.set(this, 'callInList', callInList)
      }

      const outboundList = JSON.parse((window as any).sessionStorage.getItem('cdr_outbound'))
      if (outboundList && outboundList.length > 0) {
        outboundList.forEach(item => {
          if (item.body && item.body.number) {
            item.body.hideTel = checkHideTel(item.body.number) // 缓存里面的要重新走一遍权限
          }
        })
        Vue.set(this, 'outboundList', outboundList)
      }
    }
  }

  @Action({ rawError: true })
  public async CdrLocateCust (data) {
    return commonAction({ url: '/call/action/cdr/locateCust', method: 'POST', data }).then(resp => {
      if (resp && resp.success) {
        return resp
      }
    }).catch(err => { console.log(err) })
  }

  @Action({ rawError: true })
  public async updateCardInfo (info: any) {
    this.SET_CUSTOMER_NAME({
      setType: info.cdrName,
      phone: info.phone,
      id: info.cdr.superUniqueId,
      custObj: {
        name: info.custName,
        id: info.custId,
        customerList: info.customerList
      }
    })
  }
}

export const CallCardModule = getModule(CallCardModel)
